package com.cheng.imagerelated.photoselecview.model;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;

import com.cheng.imagerelated.photoselecview.entity.Folder;
import com.cheng.imagerelated.photoselecview.entity.Image;
import com.cheng.imagerelated.photoselecview.utils.StringUtils;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ImageModel {
    /**
     * 从SDCard加载图片
     *
     * @param context
     * @param callback
     */
    public static void loadImageForSDCard(final Context context, final DataCallback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver mContentResolver = context.getContentResolver();
                Cursor mCursor = null;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    mCursor = mContentResolver.query(mImageUri, new String[]{
                                    MediaStore.Images.Media.DATA,
                                    MediaStore.Images.Media.DISPLAY_NAME,
                                    MediaStore.Images.Media.DATE_ADDED,
                                    MediaStore.Images.Media._ID},
                            null,
                            null,
                            MediaStore.Images.Media.DATE_ADDED);
                } else {
                    mCursor = mContentResolver.query(mImageUri, new String[]{
                                    MediaStore.Images.Media.DATA,
                                    MediaStore.Images.Media.DISPLAY_NAME,
                                    MediaStore.Images.Media.DATE_ADDED,
                                    MediaStore.Images.Media._ID},
                            null,
                            null,
                            MediaStore.Images.Media.DATE_ADDED);
                }

                ArrayList<Image> images = new ArrayList<>();
                //读取扫描到的图片
                if (mCursor != null) {
                    while (mCursor.moveToNext()) {
                        // 获取图片的路径
                        String path = "";
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            String id = mCursor.getString(
                                    mCursor.getColumnIndex(MediaStore.Images.Media._ID));
                            path = MediaStore.Images.Media
                                    .EXTERNAL_CONTENT_URI
                                    .buildUpon()
                                    .appendPath(String.valueOf(id))
                                    .build().toString();
                        } else {
                            path = mCursor.getString(
                                    mCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                        }

                        //获取图片名称
                        String name = mCursor.getString(
                                mCursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME));
                        //获取图片时间
                        long time = mCursor.getLong(
                                mCursor.getColumnIndex(MediaStore.Images.Media.DATE_ADDED));
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            // 保存图片 <判断当前文件是否为空>
                            if (getFilePathFromURI(context, Uri.parse(path))) {
                                Log.d(TAG, "run: " + path);
                                images.add(new Image(path, time, name));
                            }
                        } else {
                            File file = new File(path);
                            if (!".downloading".equals(getExtensionName(path)) && file.exists()) { //过滤未下载完成的文件
                                images.add(new Image(path, time, name));
                            }
                        }

                    }
                    mCursor.close();
                }
                Collections.reverse(images);
                callback.onSuccess(images);
            }
        }).start();
    }

    private static final String TAG = "ImageModel";

    /**
     * 判断当前文件是发存在
     *
     * @param context
     * @param contentUri
     * @return
     */
    public static Boolean getFilePathFromURI(Context context, Uri contentUri) {
        String fileName = getFileName(contentUri);
        if (!TextUtils.isEmpty(fileName)) {
            return copyFile(context, contentUri);
        }
        return false;
    }

    public static String getFileName(Uri uri) {
        if (uri == null) return null;
        String fileName = null;
        String path = uri.getPath();
        int cut = path.lastIndexOf('/');
        if (cut != -1) {
            fileName = path.substring(cut + 1);
        }
        return fileName;
    }

    public static Boolean copyFile(Context context, Uri srcUri) {
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(srcUri);
            if (inputStream == null) {
                return false;
            } else {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * Java文件操作 获取文件扩展名
     */
    private static String getExtensionName(String filename) {
        if (filename != null && filename.length() > 0) {
            int dot = filename.lastIndexOf('.');
            if (dot > -1 && dot < filename.length() - 1) {
                return filename.substring(dot + 1);
            }
        }
        return "";
    }

    /**
     * 把图片按文件夹拆分，第一个文件夹保存所有的图片
     *
     * @param images 集合
     * @return 图片集合
     */
    private static ArrayList<Folder> splitFolder(ArrayList<Image> images) {
        ArrayList<Folder> folders = new ArrayList<>();
        folders.add(new Folder("全部图片", images));

        if (images != null && !images.isEmpty()) {
            int size = images.size();
            for (int i = 0; i < size; i++) {
                String path = images.get(i).getPath();
                String name = getFolderName(path);
                if (StringUtils.isNotEmptyString(name)) {
                    Folder folder = getFolder(name, folders);
                    folder.addImage(images.get(i));
                }
            }
        }
        return folders;
    }


    /**
     * 根据图片路径，获取图片文件夹名称
     *
     * @param path 文件路径
     * @return 文件夹名称
     */
    private static String getFolderName(String path) {
        if (StringUtils.isNotEmptyString(path)) {
            String[] strings = path.split("/");
            if (strings.length >= 2) {
                return strings[strings.length - 2];
            }
        }
        return "";
    }


    private static Folder getFolder(String name, List<Folder> folders) {
        if (!folders.isEmpty()) {
            int size = folders.size();
            for (int i = 0; i < size; i++) {
                Folder folder = folders.get(i);
                if (name.equals(folder.getName())) {
                    return folder;
                }
            }
        }
        Folder newFolder = new Folder(name);
        folders.add(newFolder);
        return newFolder;
    }

    public interface DataCallback {
        void onSuccess(ArrayList<Image> images);
    }
}
